package com.wzxl.utils;

import com.wzxl.bean.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author rxbyes
 * @version V1.0
 * @package com.wzxl.util
 * @description: TODO ( Shiro 工具类 )
 * @date 2017 上午9:11
 */
public class ShiroUtils {

    private final static Logger LOGGER = LoggerFactory.getLogger(ShiroUtils.class);

    private static final String USER_CACHE = "user_cache";
    public static final String USER_CACHE_ID_ = "id_";

    /**
     * 获取授权主要对象
     */
    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    public static Session getSession() {
        try {
            Session session = getSubject().getSession(false);
            if (null == session) {
                return getSubject().getSession();
            }
            if (null != session) {
                return session;
            }
        } catch (InvalidSessionException e) {
            LOGGER.error("Session is not null,{}", e.getMessage());
        }
        return null;
    }

    public static User getUser() {
        User account = getUserInfo();
        if (null != account) {

        }
        return null;
    }


    /**
     * 根据ID获取用户
     *
     * @param id
     * @return 无则是null
     */
    public static User get(String id) {

        User account = (User) CacheUtil.get(USER_CACHE, USER_CACHE_ID_.concat(id));
        if (null == account) {

        }
        return null;
    }


    /**
     * 获取当前登录用户对象
     *
     * @return
     */
    public static User getUserInfo() {
        try {
            User account = (User) getSubject().getPrincipal();
            if (null != account) {
                return account;
            }
        } catch (Exception e) {
            LOGGER.error("Account is null,{}", e.getMessage());
        }
        return null;
    }


    public static Object getCache(String key) {
        return getCache(key, null);
    }

    public static Object getCache(String key, Object defaultValue) {
        Object obj = getSession().getAttribute(key);
        return obj == null ? defaultValue : obj;
    }

    public static void putCache(String key, Object value) {
        getSession().setAttribute(key, value);
    }

    public static void removeCache(String key) {
        getSession().removeAttribute(key);
    }
}
